/*semmutex_thread.c*/  
#include <pthread.h>  
#include <stdio.h>  
#include <semaphore.h>  
#include <stdlib.h>  
#include <errno.h>  
#include <unistd.h>
#define MAX 100  
static sem_t sem;  // 互斥量  
static int global = 1;  

void *t1_exe(void *arg) {  
    while (global < MAX) {  
        sem_wait(&sem);  
        printf("In thread1 before increment global=%d\n", global);  
        global++;  
        printf("In thread1 after increment global=%d\n", global);  
        sem_post(&sem);  
    }  
    sleep(5);  
    return NULL;  // 补充线程函数返回值  
}  

void *t2_exe(void *arg) {  
    while (global < MAX) {  
        sem_wait(&sem);  
        printf("In thread2 before double global=%d\n", global);  
        global *= 2;  
        printf("In thread2 after double global=%d\n", global);  
        sem_post(&sem);  
    }  
    sleep(6);  
    return NULL;  // 补充线程函数返回值  
}  

int main() {  
    pthread_t pid1, pid2;  
    int error1, error2;  
    if (sem_init(&sem, 0, 1) == -1) {  
        perror("sem initialized failed");  
        exit(0);  
    }  
    error1 = pthread_create(&pid1, NULL, t1_exe, NULL);  
    error2 = pthread_create(&pid2, NULL, t2_exe, NULL);  
    if (error1 != 0 || error2 != 0) {  
        printf("pthread_create failed ");  
        sem_destroy(&sem);  
        return -1;  // 规范错误处理返回值  
    }  
    pthread_join(pid1, NULL);  
    pthread_join(pid2, NULL);  
    sem_destroy(&sem);  
    return 0;  // 主函数规范返回值  
}  
